/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package acceso.filterX;

//import acceso.aplicacion.Bulldozer;
import static acceso.filterX.CookieFilter.cookie_name;
import acceso.hibernate.AQuery;
import acceso.hibernate.AccesoHibernate;
import acceso.util.Escritor;
import acceso.util.LogueoHelper;
import acceso.util.UserSesion;
import acceso.util.WorkflowUtil;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.hibernate.StatelessSession;
import wf.dto.ContenedorDto;
import wf3.core.Configuration;

/**
 *
 * @author john
 */
public class DummieFilter implements Filter {

    private FilterConfig filterConfig = null;
    public static String cookie_name = "";
    public static String cookie_domain = "";

    public DummieFilter() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            System.out.println("[Dummie Filter]");
            HttpServletRequest req = (HttpServletRequest) request;
            HttpServletResponse res = (HttpServletResponse) response;
            HttpSession ses = req.getSession();

            int co_conten = WorkflowUtil.convertir_entero(request.getParameter("co_conten"), 0);
            if (co_conten == 0) {
                throw new Exception("Contenedor no proporcionado o no valido.");
            }

//            if (ses.getAttribute("sesion") != null) {//tiene sesion//ELiMINAR
            if (ses.getAttribute("US") != null) {//tiene sesion
                System.out.println("[Dummie filter]Existe Sesion");
//                System.out.println("> con sesion");
//                UserSesion sesion = (UserSesion) ses.getAttribute("sesion");
                UserSesion sesion = (UserSesion) ses.getAttribute("US");
                if (sesion.isIs_dummie()) {//sesion tonta
//                    System.out.println("> con sesion > tonta");
                    if (contenedorSesion(co_conten)) {//necesita sesion
//                        System.out.println("> con sesion > tonta > modulo requiere sesion");
                        System.out.println("[DummieFilter]redireccionando a: " + req.getContextPath() + "/login/login.jsp?url=http://" + req.getHeader("HOST") + req.getRequestURI() + ((req.getQueryString() != null) ? "?" + req.getQueryString() : ""));
                        res.sendRedirect(req.getContextPath() + "/login/login.jsp?url=http://" + req.getHeader("HOST") + req.getRequestURI() + ((req.getQueryString() != null) ? "?" + req.getQueryString() : ""));
                    } else {//no necesita sesion
//                        System.out.println("> con sesion > tonta > modulo no requiere sesion");
                        chain.doFilter(request, response);
                    }
                } else {//sesion normal
                    System.out.println("> con sesion > normal");
                    chain.doFilter(request, response);
                }
            } else {//sin sesion
                System.out.println("[Dummie filter]No hay Sesion");
//                System.out.println("> sin sesion");
                if (request.getParameter("usu") != null && request.getParameter("pwd") != null) {
                    boolean r = LogueoHelper.loguear(req);
//                    System.out.println("> sin sesion | validando usu and pass::" + r);
                    if (!r) {//sino pudiste logearte ve al inicio
                        res.sendRedirect(req.getContextPath() + "/");
                    } else {
                        Cookie cookie = new Cookie(cookie_name, ((UserSesion) ses.getAttribute("US")).getId_sesion() + "");
                        cookie.setPath("/");
                        cookie.setDomain(cookie_domain);
                        cookie.setMaxAge(-1);
                        res.addCookie(cookie);
                        res.sendRedirect(req.getRequestURI() + ((req.getQueryString() != null) ? "?" + req.getQueryString() : ""));
                    }
                } else {
                    System.out.println("[Dummie filter]No hay USU ni PWD");
                    if (contenedorSesion(co_conten)) {//necesita sesion
                        System.out.println("[Dummie filter]Contenedor necesita sesion");
                        System.out.println("[Dummie filter]Redireccionando a: " + req.getContextPath() + "/login/login.jsp?url=http://" + req.getHeader("HOST") + req.getRequestURI() + ((req.getQueryString() != null) ? "?" + req.getQueryString() : ""));
                        res.sendRedirect(req.getContextPath() + "/login/login.jsp?url=http://" + req.getHeader("HOST") + req.getRequestURI() + ((req.getQueryString() != null) ? "?" + req.getQueryString() : ""));
                    } else {
                        System.out.println("[Dummie filter]Contenedor no necesita sesion");
                        UserSesion userSesion = new UserSesion();
                        ses.setAttribute("US", userSesion);
//                        ses.setAttribute("sesion", userSesion);
                        Cookie cookie = new Cookie(cookie_name, "0");
                        cookie.setPath("/");
                        cookie.setDomain(cookie_domain);
                        cookie.setMaxAge(-1);
                        res.addCookie(cookie);
                        System.out.println("[Dummie filter]Redireccionando a: " + req.getRequestURI() + ((req.getQueryString() != null) ? "?" + req.getQueryString() : ""));
                        res.sendRedirect(req.getRequestURI() + ((req.getQueryString() != null) ? "?" + req.getQueryString() : ""));
                    }
                }
            }

        } catch (IOException | ServletException ex) {
            System.out.println("[DummieFilter]Ex: " + ex);
            ex.printStackTrace();
        } catch (Exception ex) {
            Logger.getLogger(DummieFilter.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /**
     * Return the filter configuration object for this filter.
     */
    private boolean contenedorSesion(int co_conten) {
        boolean res = false;
        StatelessSession HSESSION = null;
        ContenedorDto contenedor;
        try {
            HSESSION = AccesoHibernate.getSessionFactory().openStatelessSession();
            AQuery IHQUERY = new AQuery(HSESSION.getNamedQuery("frawor2.pfconten"));
            IHQUERY.setInteger("p_co_conten", co_conten);
            Escritor.escribe_frawor(IHQUERY.getQuery());
            contenedor = (ContenedorDto) IHQUERY.getMquery().uniqueResult();
            res = contenedor.isIl_sesion();
        } catch (Exception ep) {
            res = true;
        } finally {
            FORCE_CLOSE_SESSION(HSESSION);
        }
        return res;
    }

    private void FORCE_CLOSE_SESSION(StatelessSession session) {
        try {
            if (session != null) {
                try {
                    session.connection().close();
                } catch (Exception ep) {
                    session = null;
                }
            }
        } catch (Exception ep) {
            Escritor.escribe_errors("Error grave de hibernate: " + ep.getClass() + "\n" + ep.getMessage());
        }
    }

    public FilterConfig getFilterConfig() {
        return (this.filterConfig);
    }

    /**
     * Set the filter configuration object for this filter.
     *
     * @param filterConfig The filter configuration object
     */
    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
    }

    @Override
    public void destroy() {
    }

    /**
     * Return a String representation of this object.
     */
    /**
     * Init method for this filter
     */
    @Override
    public void init(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
        cookie_name = ((Configuration) filterConfig.getServletContext().getAttribute("CFG")).getCookie_name();
        cookie_domain = ((Configuration) filterConfig.getServletContext().getAttribute("CFG")).getCookie_domain();
        System.out.println("[Dummie filter: actualizado][cookie_name:" + cookie_name + "][cookie_domain:" + cookie_domain + "]");
    }

    public synchronized static void update_filter(String cn, String cd) {
        cookie_name = cn;
        cookie_domain = cd;
        System.out.println("[Dummie filter: actualizado][cookie_name:" + cookie_name + "][cookie_domain:" + cookie_domain + "]");
    }

}
